package com.LeeCode;

/**
 * 二叉树中的最大路径和
 */

public class Code124 {
    public static void main(String[] args) {
        Integer[] arr = {2};
        TreeNode root = Utils.buildTree(arr);
        System.out.println(new Code124().maxPathSum(root));
    }

    private int ans = Integer.MIN_VALUE;

    public int maxPathSum(TreeNode root) {
        dfs(root);
        return ans;
    }

    private int dfs(TreeNode root) {
        if (root == null) return 0;
        int left = dfs(root.left);
        int right = dfs(root.right);
        ans = Math.max(ans, root.val + left + right);

        return Math.max(Math.max(left, right) + root.val, 0);
    }
}
